/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JTAgendaContactos.java
 *
 * Created on Apr 12, 2011, 9:32:24 PM
 */

package german.forms;

import german.dao.ContactoDao;
import german.logica.Contacto;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author german
 */
public class JTAgendaContactos extends javax.swing.JFrame {


    DefaultTableModel tablaContactos = new DefaultTableModel(null, new String[]{"id", "name", "address", "tel", "email", "sex"});
    ArrayList<Contacto> contactos;
    ListSelectionModel lsmContactos;

    /** Creates new form JTAgendaContactos */
    public JTAgendaContactos() {
        initComponents();
        desabilitaDatos();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLid = new javax.swing.JLabel();
        jLname = new javax.swing.JLabel();
        jLaddress = new javax.swing.JLabel();
        jLtel = new javax.swing.JLabel();
        jLemail = new javax.swing.JLabel();
        jLsex = new javax.swing.JLabel();
        jTid = new javax.swing.JTextField();
        jTname = new javax.swing.JTextField();
        jTaddress = new javax.swing.JTextField();
        jTtel = new javax.swing.JTextField();
        jTemail = new javax.swing.JTextField();
        jTsex = new javax.swing.JTextField();
        jBsearch = new javax.swing.JButton();
        jTsearch = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTbtable = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jBnew = new javax.swing.JButton();
        jBmodify = new javax.swing.JButton();
        jBremove = new javax.swing.JButton();
        jBsave = new javax.swing.JButton();
        jBexit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos de Contacto"));

        jLid.setText("Id");

        jLname.setText("Nombre");

        jLaddress.setText("Dirección");

        jLtel.setText("Tel");

        jLemail.setText("Email");

        jLsex.setText("Sexo");

        jTsex.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTsexActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLid)
                        .addGap(66, 66, 66)
                        .addComponent(jTid, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLname)
                            .addComponent(jLaddress))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTaddress, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
                            .addComponent(jTname, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE))))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLsex)
                    .addComponent(jLemail)
                    .addComponent(jLtel))
                .addGap(41, 41, 41)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTtel, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
                    .addComponent(jTemail, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
                    .addComponent(jTsex, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(106, 106, 106))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLid)
                            .addComponent(jTid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLname)
                            .addComponent(jTname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLaddress)
                            .addComponent(jTaddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLtel)
                            .addComponent(jTtel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLemail)
                            .addComponent(jTemail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLsex)
                            .addComponent(jTsex, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(30, Short.MAX_VALUE))
        );

        jBsearch.setText("Buscar");
        jBsearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBsearchActionPerformed(evt);
            }
        });

        jTbtable.setModel(tablaContactos);
        jTbtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lsmContactos = jTbtable.getSelectionModel();
        lsmContactos.addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent e){
                if(! e.getValueIsAdjusting()){
                    jTTtablaLineaSeleccionada(jTbtable);
                }
            }

        });
        jScrollPane1.setViewportView(jTbtable);

        jBnew.setText("Nuevo");
        jBnew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBnewActionPerformed(evt);
            }
        });

        jBmodify.setText("Modificar");
        jBmodify.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBmodifyActionPerformed(evt);
            }
        });

        jBremove.setText("Eliminar");
        jBremove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBremoveActionPerformed(evt);
            }
        });

        jBsave.setText("Guardar");
        jBsave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBsaveActionPerformed(evt);
            }
        });

        jBexit.setText("Salir");
        jBexit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBexitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(123, 123, 123)
                .addComponent(jBnew)
                .addGap(18, 18, 18)
                .addComponent(jBmodify)
                .addGap(18, 18, 18)
                .addComponent(jBremove)
                .addGap(18, 18, 18)
                .addComponent(jBsave)
                .addGap(18, 18, 18)
                .addComponent(jBexit)
                .addContainerGap(112, Short.MAX_VALUE))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jBexit, jBmodify, jBnew, jBremove, jBsave});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBnew)
                    .addComponent(jBmodify)
                    .addComponent(jBremove)
                    .addComponent(jBsave)
                    .addComponent(jBexit))
                .addContainerGap(26, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTsearch, javax.swing.GroupLayout.PREFERRED_SIZE, 435, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 161, Short.MAX_VALUE)
                        .addComponent(jBsearch, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 692, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTsearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBsearch))
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(40, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTsexActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTsexActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTsexActionPerformed

    private void jBnewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBnewActionPerformed
        habilitaDatos();
        jTid.setText("");
        jTname.setText("");
        jTaddress.setText("");
        jTtel.setText("");
        jTemail.setText("");
        jTsex.setText("");
    }//GEN-LAST:event_jBnewActionPerformed

    private void desabilitaDatos(){
        jTid.setEditable(false);
        jTname.setEditable(false);
        jTaddress.setEditable(false);
        jTtel.setEditable(false);
        jTemail.setEditable(false);
        jTsex.setEditable(false);
    }

    private void habilitaDatos(){
        jTname.setEditable(true);
        jTaddress.setEditable(true);
        jTtel.setEditable(true);
        jTemail.setEditable(true);
        jTsex.setEditable(true);
    }

    public boolean verificarDatos(){
        if (!jTname.getText().equals("") && !jTaddress.getText().equals("")){
            return true;
        }
        else{
            JOptionPane.showMessageDialog(null, "Dato nombre o dato direccion no fue escrito");
            return false;
        }
    }

    private void jTTtablaLineaSeleccionada(JTable tabla){
        if(jTbtable.getSelectedRow() != -1){
            habilitaDatos();
            jTid.setText(String.valueOf(contactos.get(tabla.getSelectedRow()).getId()));
            jTname.setText(contactos.get(tabla.getSelectedRow()).getName());
            jTaddress.setText(contactos.get(tabla.getSelectedRow()).getAddress());
            jTtel.setText(contactos.get(tabla.getSelectedRow()).getTel());
            jTemail.setText(contactos.get(tabla.getSelectedRow()).getEmail());
            jTsex.setText(contactos.get(tabla.getSelectedRow()).getSex());
        }
        else{
            jTid.setText("");
            jTname.setText("");
            jTaddress.setText("");
            jTtel.setText("");
            jTemail.setText("");
            jTsex.setText("");
        }
    }

    public void listarContactos() throws SQLException{
        ContactoDao cDao = new ContactoDao();
        contactos = cDao.getLista("%" + jTsearch.getText() + "%");
        mostrarBusqueda(contactos);
    }

    public void guardar(){
        try {
            Contacto c1 = new Contacto();
            c1.setName(jTname.getText());
            c1.setAddress(jTaddress.getText());
            c1.setTel(jTtel.getText());
            c1.setEmail(jTemail.getText());
            c1.setSex(jTsex.getText());
            ContactoDao c1Dao = new ContactoDao();
            c1Dao.agregar(c1);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Error al guardar" + ex);
        }
    }

    private void jBsaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBsaveActionPerformed
        if(verificarDatos()){
            guardar();
            desabilitaDatos();
            try {
                listarContactos();
            } catch (SQLException ex) {
                Logger.getLogger(JTAgendaContactos.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jBsaveActionPerformed

    private void jBsearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBsearchActionPerformed
        try {
            listarContactos();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Error al buscar" + ex);
        }
    }//GEN-LAST:event_jBsearchActionPerformed

    private void jBremoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBremoveActionPerformed
        try {
            eliminarContacto();
            listarContactos();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Error al eliminar" + ex);
        }
    }//GEN-LAST:event_jBremoveActionPerformed

    private void jBmodifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBmodifyActionPerformed
        try {
            modificarContacto();
            listarContactos();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Error al modificar" + ex);
        }
    }//GEN-LAST:event_jBmodifyActionPerformed

    private void jBexitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBexitActionPerformed
        int resp = JOptionPane.showConfirmDialog(this, "Desea realmente salir de la aplicacion?",
                "Confirmacion", JOptionPane.YES_NO_OPTION);
        if (resp == JOptionPane.YES_NO_OPTION) {
            
        }
    }//GEN-LAST:event_jBexitActionPerformed

    public void modificarContacto() throws SQLException{
        if(jTbtable.getSelectedRow() != 1){
            if(verificarDatos()){
                Contacto c1 = new Contacto();
                ContactoDao c1Dao = new ContactoDao();
                c1.setId(Long.valueOf(jTid.getText()));
                c1.setName(jTname.getText());
                c1.setAddress(jTaddress.getText());
                c1.setTel(jTtel.getText());
                c1.setEmail(jTemail.getText());
                c1.setSex(jTsex.getText());
                c1Dao.modificar(c1);
                JOptionPane.showMessageDialog(null, "Contacto agregado con exito");
            }
        }
    }

    public void eliminarContacto() throws SQLException{
        int resp = JOptionPane.showConfirmDialog(this, "Desea realmente eliminar este contaco?",
                "Confirmacion", JOptionPane.YES_NO_OPTION);
        if (resp == JOptionPane.YES_NO_OPTION) {
            ContactoDao cDao = new ContactoDao();
            cDao.eliminar(contactos.get(jTbtable.getSelectedRow()));
            mostrarBusqueda(contactos);
        }
    }



    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JTAgendaContactos().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBexit;
    private javax.swing.JButton jBmodify;
    private javax.swing.JButton jBnew;
    private javax.swing.JButton jBremove;
    private javax.swing.JButton jBsave;
    private javax.swing.JButton jBsearch;
    private javax.swing.JLabel jLaddress;
    private javax.swing.JLabel jLemail;
    private javax.swing.JLabel jLid;
    private javax.swing.JLabel jLname;
    private javax.swing.JLabel jLsex;
    private javax.swing.JLabel jLtel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTaddress;
    private javax.swing.JTable jTbtable;
    private javax.swing.JTextField jTemail;
    private javax.swing.JTextField jTid;
    private javax.swing.JTextField jTname;
    private javax.swing.JTextField jTsearch;
    private javax.swing.JTextField jTsex;
    private javax.swing.JTextField jTtel;
    // End of variables declaration//GEN-END:variables

    private void mostrarBusqueda(ArrayList<Contacto> contactos) {
        while(tablaContactos.getRowCount() > 0){
            tablaContactos.removeRow(0);
        }

        if(contactos.isEmpty()){
            JOptionPane.showMessageDialog(null, "Ningun contacto encontrado");
        }
        else{
            String[] linea = new String[]{null, null, null, null, null, null};
            for (int i = 0; i < contactos.size(); i++){
                tablaContactos.addRow(linea);
                tablaContactos.setValueAt(contactos.get(i).getId(), i, 0);
                tablaContactos.setValueAt(contactos.get(i).getName(), i, 1);
                tablaContactos.setValueAt(contactos.get(i).getAddress(), i, 2);
                tablaContactos.setValueAt(contactos.get(i).getTel(), i, 3);
                tablaContactos.setValueAt(contactos.get(i).getEmail(), i, 4);
                tablaContactos.setValueAt(contactos.get(i).getSex(), i, 5);
            }
         }
    }

}
